package com.github.thinwonton.spring.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.github.thinwonton.spring.annotation.AvoidMultipalSubmit;
import com.github.thinwonton.spring.utils.TokenProcessor;

/**
 * 防止重复提交表单拦截器
 * 
 * @author hugo
 *
 */
public class AvoidMultipalSubmitHandlerInterceptor extends HandlerInterceptorAdapter {
	private static final String TOKEN = "token";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			// 获取方法上的注解
			AvoidMultipalSubmit annotation = method.getAnnotation(AvoidMultipalSubmit.class);
			if (annotation != null) {
				// 在session保存token
				if (annotation.preHandle()) {
					request.getSession().setAttribute(TOKEN, TokenProcessor.getInstance().generate());
				}

				// 防止重复提交
				if (annotation.avoid()) {
					if (isMultipleSubmit(request)) {
						return false;
					}

					request.getSession().removeAttribute(TOKEN);
				}

			}
		}

		return true;
	}

	/**
	 * 判断是否重复提交表单
	 * 
	 * @param request
	 * @return
	 */
	private boolean isMultipleSubmit(HttpServletRequest request) {
		String serverToken = (String) request.getSession().getAttribute(TOKEN);
		if (serverToken == null) {
			return true;
		}
		String clinetToken = request.getParameter(TOKEN);
		if (clinetToken == null || !serverToken.equals(clinetToken)) {
			return true;
		}
		return false;
	}
}
